//吊起设备原生相机相册取得文件,并自动上传七牛，返回七牛key，domain，本地file信息
function getPhoto(token, type = 2, count = 1, showLoading = true) {
  return new Promise((resolve, reject) => {
    let types = [['camera'], ['album'] , ['album', 'camera']]
    let sourceType = types[type]
    uni.chooseImage({
      count: count, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, //从相册选择
      success: function(res) {
        if (showLoading) {
          uni.showLoading({
            title: '上传中...',
          })
        }
        console.log('-------------:', res)
        uploads(res.tempFiles, token)
          .then((result) => {
            let keys = []
            let urls = []
            if (result) {
              for (var item of result) {
                keys.push(item.key)
                urls.push(item.url)
              }
            }
            resolve({
              key: keys,
              files: urls
            })
          })
          .catch((msg) => {
            reject(msg)
          })

        // var state = 0 // 上传第几张图片
        // var imgList = [] // 保存图片数组
        // var uploadNum = res.tempFiles.length // 上传数组的长度
        // //上传七牛
        // for (let i = 0; i < uploadNum; i++) {
        //   let filePath = res.tempFiles[i].path //为需要上传的文件
        //   upload(filePath, token)
        //     .then((msg) => {
        //       //最后七牛返回的key
        //       state++
        //       imgList.push(msg)
        //       if (state == uploadNum) {
        //         resolve({
        //           key: imgList,
        //           files: res.tempFiles,
        //         })
        //       }
        //     })
        //     .catch((msg) => {
        //       reject(msg)
        //     })
        // }
      },
      complete: function() {},
    })
  })
}

function uploadOneWHPhoto(token, type = 2, block) {
  return new Promise((resolve, reject) => {
    let types = [['camera'], ['album'] , ['album', 'camera']]
    let sourceType = types[type]
    uni.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, //从相册选择
      success: function(res) {
        if (res.tempFilePaths.length > 0) {
          let filePath = res.tempFilePaths[0]
          uni.getImageInfo({
            src: filePath,
            success: function (image) {
              var key = new Date().getTime() + Math.random(1000) + filePath.split('/').pop().replace(/\_/g, '') //key为自定义文件名
              key = key.replace(/\.(?=.*\.)/g, '')
              key = key.replace(/\./, `_${image.width}_${image.height}_.`)
              if (block) block(filePath, key)
              uni.uploadFile({
                url: uploadUrl, // default ecn华北的地址，在七牛云中选择对应位置的网址
                filePath: filePath,
                name: 'file',
                formData: {
                  token: token,
                  key: 'upload-image/' + key,
                },
                complete: (res) => {
                  if (res.statusCode === 200) {
                    resolve(JSON.parse(res.data).key || JSON.parse(res.data).src)
                  } else {
                    reject(res.errMsg)
                  }
                },
              })
            }
        });

        }

      },
      complete: function() {},
    })
  })
}

function uploads(list, token) {
  return new Promise((resolve, reject) => {
    var state = 0 // 上传第几张图片
    var imgList = [] // 保存图片数组
    var uploadNum = list.length // 上传数组的长度
    //上传七牛
    for (let i = 0; i < uploadNum; i++) {
      let filePath = list[i].path || list[i].url //为需要上传的文件
      upload(filePath, token)
        .then((msg) => {
          //最后七牛返回的key
          state++
          imgList.push({key: msg, url: filePath})
          if (state == uploadNum) {
            resolve(imgList)
          }
        })
        .catch((msg) => {
          reject(msg)
        })
    }
  })
}

const uploadUrl = 'https://up-z2.qiniup.com'
//上传七牛
function upload(filePath, token, duration = '') {
  return new Promise((resolve, reject) => {
    var key = new Date().getTime() + Math.random(1000) + filePath.split('/').pop().replace(/\=/g, '') //key为自定义文件名
    key = key.replace(/\.(?=.*\.)/g, '')
    if (duration) key = key.replace(/\./, `durationTime=${duration * 1000}.`)
    uni.uploadFile({
      url: uploadUrl, // default ecn华北的地址，在七牛云中选择对应位置的网址
      filePath: filePath,
      name: 'file',
      formData: {
        token: token,
        key: 'upload-image/' + key,
      },
      complete: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data).key || JSON.parse(res.data).src)
        } else {
          reject(res.errMsg)
        }
      },
    })
  })
}

export default {
  uploadUrl,
  upload,
  uploads,
  getPhoto,
  uploadOneWHPhoto
}
